<?php
/*
  This page does double duty as the intro and professional location pages.  The core
  is the same, w/ only a few bells and whistles separating the two based on $_REQUEST['page'] == 'proLocation'.
*/
?>

<?php
  $alertNoParcelNum = false;
  if (isset($_COOKIE['noParcelNum'])) {
    $alertNoParcelNum = true;
    setcookie('noParcelNum','',time() - 3600);
  }
  $isRegistered = isset($_SESSION['gdusername']) AND isset($_SESSION['gdpassword']);

  include_once('util.php');
  $glossary = buildGlossary('Location');
?>

  <body onload="Ext.onReady(function(){init()})">
    <script>
      var isRegistered = <?php echo json_encode($isRegistered)?>;
      var soilsLegend = {
         'A'        : '#008080' // teal '#8C510A'
        ,'B'        : '#00FFFF' // cyan '#D8B365'
        ,'C'        : '#D2B48C' // tan '#F6E8C3'
        ,'C/D'      : '#FFEBCD' // blanchedalmond '#5AB4AC'
        ,'D'        : '#A52A2A' // brown '#C7EAE5'
        ,'Unlisted' : '#545454' // grey '#01665E' 
      };
      var showUnregulatedRadioGroup = <?php echo json_encode($_REQUEST['page'] == 'proLocation')?>;
      function init() {
        // where did we come from
        document.getElementById('prevStep').href = '<?php echo $_REQUEST['page'] == 'introLocation' ? '?page=introGuide' : '?page=learn'?>';
        // and where do we go
        var nextStepHref = document.getElementById('nextStep').href = '<?php echo $_REQUEST['page'] == 'introLocation' ? '?page=introRegulated' : '?page=proSolution'?>';

        Ext.get('loading').fadeOut({duration : 0.2,remove : true});
        Ext.QuickTips.init();

        var cp = new Ext.state.CookieProvider({
          expires : new Date(new Date().getTime()+(1000*60*60*24*30)) //30 days
        });
        Ext.state.Manager.setProvider(cp);

        var proj4326   = new OpenLayers.Projection('EPSG:4326');
        var proj900913 = new OpenLayers.Projection('EPSG:900913');

        // this is the free text entry field which fires svc/search.php to fill the table
        var searchField = new Ext.ux.form.SearchField({
           emptyText       : (isRegistered ? 'Search by owner name or address' : 'Search by address')
          ,width           : 387
          ,renderTo        : 'searchField'
          ,hideTrigger1    : false
          ,store           : new Ext.data.JsonStore({
             url        : 'svc/search.php'
            ,root       : 'data'
            ,idProperty : 'id'
            ,fields     : ['id','parcels','neLon','neLat','swLon','swLat']
            ,baseParams : {
              isRegistered : isRegistered
            }
            ,listeners  : {load : function(store) {
              if (store.baseParams.query != '' && store.getCount() > 0) {
                var rec = store.getAt(0);
                var parcels = rec.get('parcels');
                // Got parcels?  Load them into the store,i.e. the table.
                if (parcels) {
                  var parcelsStore = parcelsOnMapGridPanel.getStore();
                  parcelsStore.removeAll();
                  var recs = [];
                  for (var i = 0; i < parcels.length; i++) {
                    recs.push(new parcelsStore.recordType({
                       'Parcel Num'             : parcels[i]['Parcel Num']
                      ,'Regulated'              : parcels[i]['Regulated']
                      ,'Owner Name'             : parcels[i]['Owner Name']
                      ,'Actual Removal (lb/yr)' : parcels[i]['Actual Removal (lb/yr)']
                      ,'Phys Addr1'             : parcels[i]['Phys Addr1']
                      ,'Phys City'              : parcels[i]['Phys City']
                    }));
                  };
                  parcelsStore.add(recs);
                }
                else if (rec.get('swLon') == '' || rec.get('swLat') == '' || rec.get('neLon') == '' || rec.get('neLat') == '') {
                  Ext.Msg.alert('Search',"We're sorry, but no seach results were found.");
                }
                else if (!new OpenLayers.Bounds(-71.564,42.017,-71.359,42.191).containsBounds(new OpenLayers.Bounds(rec.get('swLon'),rec.get('swLat'),rec.get('neLon'),rec.get('neLat')))) {
                  Ext.Msg.alert('Search',"We're sorry, but the search results were not completely contained within the Milford/Franklin/Bellingham area.");
                }
                else {
                  map.zoomToExtent(new OpenLayers.Bounds(rec.get('swLon'),rec.get('swLat'),rec.get('neLon'),rec.get('neLat')).transform(proj4326,proj900913));
                }
              }
            }}
          })
        });

        // Do what it says, reset everything.
        new Ext.Button({
           renderTo : 'resetButton'
          ,text     : 'Reset map and fields'
          ,width    : 130
          ,height   : 30
          ,handler  : function() {
            document.getElementById('nextButton').src = 'images/next_but_grey.png';
            document.getElementById('nextStep').href = 'javascript:void(0)';
            document.getElementById('parcelInfo').innerHTML = '';
            searchField.reset();
            parcelInfoStore.removeAll();
            var lyr = map.getLayersByName('Parcel')[0];
            lyr.removeFeatures(lyr.features);
            cp.clear('parcelNum');
            cp.clear('parcelThumbnail');
            Ext.getCmp('showSoilTypesRadioGroup').items.items[0].setValue(true);
            Ext.getCmp('showUnregulatedRadioGroup').suspendEvents();
            Ext.getCmp('showUnregulatedRadioGroup').items.items[0].setValue(true);
            Ext.getCmp('showUnregulatedRadioGroup').resumeEvents();
            map.zoomToExtent(new OpenLayers.Bounds(-71.564868011524,41.995072541334,-71.291583099426,42.183100716774).transform(proj4326,proj900913));
          }
        });

        // Once a row has been selected, parcelInfoStore will contain all the parcel info goodies.
        var parcelInfoStore = new Ext.data.JsonStore({
           url           : 'svc/getParcelInfo.php'
          ,root          : 'data'
          ,totalProperty : 'count'
          ,idProperty    : 'ParcelNum'
          ,fields        : [
             'Parcel Num'
            ,'Regulated'
            ,'Owner Name'
            ,'Phys Addr1'
            ,'Phys City'
            ,'Dep2HWT (in)'
            ,'Dep2ResLyr (in)'
            ,'Hyd Soil Group'
            ,'KSat (in/hr)'
            ,'Imperv Area (ac)'
            ,'UpLand Area (ac)'
            ,'Wetland Area (ac)'
            ,'Total Area (ac)'
            ,'Perv Load (lb/yr)'
            ,'Imperv Load'
            ,'Total Load (lb/yr)'
            ,'Slope (%)'
            ,'posList'
            ,'Load Credit/Deficit (lb/yr)'
          ]
          ,listeners : {
            beforeload : function(sto) {
              // clear out everything
              document.getElementById('parcelInfo').innerHTML = '';
              document.getElementById('nextButton').src = 'images/next_but_grey.png';
              document.getElementById('nextStep').href = 'javascript:void(0)';
              var lyr = map.getLayersByName('Parcel')[0];
              lyr.removeFeatures(lyr.features);
              cp.clear('parcelNum');
              cp.clear('parcelThumbnail');
              cp.clear('stormwater');
              cp.clear('goal');
              cp.clear('stormwaterShort');
              cp.clear('stormwaterFull');
              cp.clear('pollution');
              cp.clear('totalCost');
            }
            ,load      : function(sto) {
              // We love cookies.  Fill out all the cookies w/ this parcel's info.  Cookies are used to talk from page to page.
              if (sto.getCount() > 0) {
                cp.set('parcelNum',sto.getAt(0).get('Parcel Num'));
                cp.set('parcelRegulated',sto.getAt(0).get('Regulated'));
                cp.set('parcelOwner Name',sto.getAt(0).get('Owner Name'));
                cp.set('parcelPhys Addr1',sto.getAt(0).get('Phys Addr1'));
                cp.set('parcelPhys City',sto.getAt(0).get('Phys City'));
                cp.set('parcelDep2HWT (in)',sto.getAt(0).get('Dep2HWT (in)'));
                cp.set('parcelDep2ResLyr (in)',sto.getAt(0).get('Dep2ResLyr (in)'));
                cp.set('parcelHyd Soil Group',sto.getAt(0).get('Hyd Soil Group'));
                cp.set('parcelKSat (in/hr)',sto.getAt(0).get('KSat (in/hr)'));
                cp.set('parcelImperv Area (ac)',sto.getAt(0).get('Imperv Area (ac)'));
                cp.set('parcelUpLand Area (ac)',sto.getAt(0).get('UpLand Area (ac)'));
                cp.set('parcelWetland Area (ac)',sto.getAt(0).get('Wetland Area (ac)'));
                cp.set('parcelTotal Area (ac)',sto.getAt(0).get('Total Area (ac)'));
                cp.set('parcelPerv Load (lb/yr)',sto.getAt(0).get('Perv Load (lb/yr)'));
                cp.set('parcelImperv Load',sto.getAt(0).get('Imperv Load'));
                cp.set('parcelTotal Load (lb/yr)',sto.getAt(0).get('Total Load (lb/yr)'));
                cp.set('parcelSlope (%)',sto.getAt(0).get('Slope (%)'));
                cp.set('parcelLoad Credit/Deficit (lb/yr)',sto.getAt(0).get('Load Credit/Deficit (lb/yr)'));
                if (sto.getAt(0).data['posList'] == ' ' || sto.getAt(0).data['posList'] == '') {
                  Ext.Msg.alert('Parcel search',"We're sorry, but no recognized parcel was found.");
                  sto.setBaseParam('point','');
                  sto.setBaseParam('click','');
                  return;
                }
                var a = sto.getAt(0).data;
                var ls;
                for (var i in a) {
                  if (i == 'posList') {
                    // Save the parcel geometry for thumbnails.
                    var g1 = [];
                    var g0 = [];
                    var p = a[i].split(' ');
                    for (var j = 0; j < p.length - 1; j += 2) {
                      g0.push(new OpenLayers.Geometry.Point(p[j+1],p[j]));
                      g1.push(new OpenLayers.Geometry.Point(p[j+1],p[j]).transform(proj4326,proj900913));
                    }
                    var ring = new OpenLayers.Geometry.LinearRing(g1);
                    ls       = new OpenLayers.Geometry.LineString(g0);
                    // simplify the geom if it is too cumbersome
                    if (g0.length > 200) {
                      ls = ls.simplify(0.001);
                    }
                    if (g0.length > 15) {
                      ls = ls.simplify(0.0002);
                    }
                    if (sto.baseParams.click == '') {
                      map.zoomToExtent(ring.getBounds());
                    }
                    else {
                      parcelsOnMapGridPanel.getStore().load();
                    }
                    map.getLayersByName('Parcel')[0].addFeatures(new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Polygon([ring])));
                  }
                }
                var thumbnail = 'https://maps.googleapis.com/maps/api/staticmap?size=100x100&sensor=false&path=weight:1|fillcolor:0x0000AA11|color:0x0000FFBB';
                var v = ls.getVertices();
                for (var i = 0; i < v.length; i++) {
                  thumbnail += '|' + v[i].y + ',' + v[i].x;
                }
                cp.set('parcelThumbnail',thumbnail);
                // fill in the parcel info section
                var rec = sto.getAt(0); 
                var siteInfo = [
                  '<div id="part_one">'
                    ,'<p class="heading">Site Information</p>'
                    ,'<p><label class="item">Address:</label><label id="1">' + rec.get('Phys Addr1') + ', ' + rec.get('Phys City') + '</label></p>'
                  ,'</div>'
                ];
                if (isRegistered) {
                  siteInfo = [
                    '<div id="part_one">'
                      ,'<p class="heading">Site Information</p>'
                      ,'<p><label class="item">Parcel No:</label><label id="1">' + rec.get('Parcel Num') + '</label></p>'
                      ,'<p><label class="item">Owner Name:</label><label id="2">' + rec.get('Owner Name') + '</label></p>'
                    ,'</div>'
                  ];
                }
                var soil = [
                   '<p class="heading">Average Soil Properties</p>'
                  ,'<table>'
                    ,'<tr><td>Depth to High Water Table (in)</td><td>' + Math.round(100 * rec.get('Dep2HWT (in)')) / 100 + '</td></tr>'
                    ,'<tr><td>Depth to Restrictive Layer (in)</td><td>' + Math.round(100 * rec.get('Dep2ResLyr (in)') * 100) / 100 + '</td></tr>'
                    ,'<tr><td>Hydrologic Soil Group</td><td>' + rec.get('Hyd Soil Group') + '</td></tr>'
                    ,'<tr><td>Saturated Hydraulic Cond. (in/hr)</td><td>' + Math.round(100 * rec.get('KSat (in/hr)') * 100) / 100 + '</td></tr>'
                  ,'</table>'
                ];
                var landUse = [
                   '<p class="heading">Land Use Areas</p>'
                  ,'<table>'
                    ,'<tr><td>Impervious Area (ac)</td><td>' + Math.round(100 * rec.get('Imperv Area (ac)') * 100) / 100 + '</td></tr>'
                    ,'<tr><td>Upland Area (ac)</td><td>' + Math.round(100 * rec.get('UpLand Area (ac)') * 100) / 100 + '</td></tr>'
                    ,'<tr><td>Wetland Area (ac)</td><td>' + Math.round(100 * rec.get('Wetland Area (ac)') * 100) / 100 + '</td></tr>'
                    ,'<tr><td>Total Area (ac)</td><td>' + Math.round(100 * rec.get('Total Area (ac)') * 100) / 100 + '</td></tr>'
                  ,'</table>'
                ];
                var phosphorous = [
                   '<p class="heading">Phosphorous Load Rates</p>'
                  ,'<table>'
                    ,'<tr><td>Impervious Load Rate (lb/ac/yr)</td><td>' + Math.round(100 * rec.get('Imperv Load') * 100) / 100 + '</td></tr>'
                    ,'<tr><td>Pervious Load Rate Area (lb/ac/yr)</td><td>' + Math.round(100 * rec.get('Perv Load (lb/yr)') * 100) / 100 + '</td></tr>'
                    ,'<tr><td>Total Load Rate (lb/ac/yr)</td><td>' + Math.round(100 * rec.get('Total Load (lb/yr)') * 100) / 100 + '</td></tr>'
                  ,'</table>'
                ];
                document.getElementById('nextButton').src = 'images/next_but.png';
                document.getElementById('nextStep').href = nextStepHref;
                document.getElementById('parcelInfo').innerHTML = [
                  '<div id="site_information">'
                    ,siteInfo.join('')
<?php
  if ($_REQUEST['page'] == 'proLocation') {
?>
                    ,soil.join('')
                    ,landUse.join('')
                    ,phosphorous.join('')
<?php
  }
?>
                  ,'</div>'
<?php
  if ($_REQUEST['page'] == 'proLocation') {
?>
                  ,'<p style="text-align: center; margin-top: 8px;"><a class="info" id="data used to make this recommendation" href="#">Where does this data come from?</a></p>'
<?php
  }
?>
                ].join('');
                $("div#site_information table tr:odd td").css("background-color", "#F0DDDD");
                var clickHereLinks = initClickHereLinks('introLocation');
                infoWindow = $('table#info-window');
                $('a.info').click(function(e){
                  e.preventDefault();
                  $('table#info-window tr:eq(1) td:first').html(clickHereLinks[$(this).attr('id')]);
                  infoWindow.show()
                });
                $('table#info-window tr td a').click(function(e){
                  e.preventDefault();
                  infoWindow.hide();
                });
                $('body').live('keydown', function (e) {
                    if (infoWindow.css('display') != 'none'){
                        var charCode = e.charCode || e.keyCode;
                        if (charCode == 27)
                            infoWindow.css('display', 'none');
                    }
                });
              }
            }
          }
        });

        var unregulatedVisible = showUnregulatedRadioGroup ? (cp.get('unregulatedVisible') ? cp.get('unregulatedVisible') == 'yes' : true) : true;

        var col = [
           {dataIndex : 'Phys Addr1',header : 'Address',id : 'address'}
          ,{dataIndex : 'Phys City' ,header : 'City'   ,id : 'city'   ,width : 75}
        ];
        if (isRegistered) {
          col = [{dataIndex : 'Owner Name',header : 'Owner Name',id : 'ownerName'}];
        }

        // The parcel listing is populated by the map's bbox w/ the results coming from svc/getParcelsByBbox.php.
        var parcelsOnMapGridPanel = new Ext.grid.GridPanel({
          store             : new Ext.data.JsonStore({
             url           : 'svc/getParcelsByBbox.php'
            ,root          : 'data'
            ,totalProperty : 'count'
            ,idProperty    : 'ParcelNum'
            ,remoteSort    : true
            ,fields        : [
               'Parcel Num'
              ,'Regulated'
              ,'Owner Name'
              ,'Phys Addr1'
              ,'Phys City'
              ,'Actual Removal (lb/yr)'
            ]
            ,listeners     : {
              beforeload : function(sto) {
                // clean start
                var bbox = map.getExtent().transform(proj900913,proj4326).toArray();
                sto.setBaseParam('swLon',bbox[0]);
                sto.setBaseParam('swLat',bbox[1]);
                sto.setBaseParam('neLon',bbox[2]);
                sto.setBaseParam('neLat',bbox[3]);
                sto.setBaseParam('sort',(isRegistered ? 'Owner Name' : 'Phys Addr1'));
                sto.setBaseParam('dir','ASC');
                sto.setBaseParam('regulatedOnly',!unregulatedVisible);
              }
              ,load      : function(sto) {
                if (sto.getCount() == 0) {
                  Ext.Msg.alert('No parcels found','Not seeing results you expect? The Parcel table only lists parcels visible in the map window.  Consider zooming out to include more coverage for your search.  You can also try clearing your parcel search string (by clicking on the X to the right of the search field).');
                }
                else {
                  Ext.defer(function() {
                    // If we found something, highlight the record on the list.
                    if (parcelInfoStore.getCount() > 0) {
                      var idx = parcelsOnMapGridPanel.getStore().find('Parcel Num',parcelInfoStore.getAt(0).get('Parcel Num'));
                      if (idx >= 0) {
                        parcelsOnMapGridPanel.getView().focusRow(idx);
                        parcelsOnMapGridPanel.getSelectionModel().selectRow(idx);
                      }
                    }
                  },750);
                }
              }
            }
          })
          ,columns          : col
          ,stripeRows       : true
          ,autoExpandColumn : (isRegistered ? 'ownerName' : 'address')
          ,loadMask         : true
          ,remoteSort       : true
          ,renderTo         : 'parcelsOnMapGridPanel'
          ,border           : false
          ,enableHdMenu     : false
          ,height           : 354
          ,sm               : new Ext.grid.RowSelectionModel({singleSelect : true})
          ,listeners        : {
            rowclick : function(grid,rowIndex,e) {
              // When a record is selected on the table, tell the parcel store to go get it.
              parcelInfoStore.setBaseParam('query',grid.getStore().getAt(rowIndex).get('Parcel Num'));
              parcelInfoStore.setBaseParam('point','');
              parcelInfoStore.setBaseParam('click','');
              parcelInfoStore.load();
            }
          }
        });

        var soilsVisible       = cp.get('soilsVisible') ? cp.get('soilsVisible') == 'yes' : true;

        // initilize the interactive map
        var map = new OpenLayers.Map('map',{
          layers   : [
             new OpenLayers.Layer.Google('Google Map',{opacity : 0.9,numZoomLevels : 20})
            ,new OpenLayers.Layer.WMS(
              'soils'
              ,'http://geo.bluecityexchange.org/geoserver/crwa/wms'
              ,{
                 layers      : 'crwa:soils'
                ,styles      : ''
                ,srs         : 'EPSG:900913'
                ,format      : 'image/png'
                ,transparent : true
              }
              ,{isBaseLayer : false,opacity : 0.4,visibility : soilsVisible}
            )
            ,new OpenLayers.Layer.WMS(
              'watershed'
              ,'http://geo.bluecityexchange.org/geoserver/crwa/wms'
              ,{
                 layers      : 'crwa:watershed'
                ,styles      : ''
                ,srs         : 'EPSG:900913'
                ,format      : 'image/png'
                ,transparent : true
              }
              ,{isBaseLayer : false,opacity : 0.5}
            )
            ,new OpenLayers.Layer.WMS(
              'towns'
              ,'http://geo.bluecityexchange.org/geoserver/crwa/wms'
              ,{
                 layers      : 'crwa:town'
                ,styles      : ''
                ,srs         : 'EPSG:900913'
                ,format      : 'image/png'
                ,transparent : true
              }
              ,{isBaseLayer : false,opacity : 0.75}
            )
            ,new OpenLayers.Layer.Vector('Parcel',{styleMap : new OpenLayers.StyleMap({strokeColor : "blue",strokeWidth : 4,strokeOpacity : 0.6,fillOpacity : 0})})
          ]
          ,projection        : proj900913
          ,displayProjection : proj4326
          ,units             : 'm'
          ,maxResolution     : 'auto'
          ,maxExtent         : new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508.34)
        });

        // Respond to a map click by trying to load a parcel that contains the lon,lat.
        map.events.register('click',this,function(e) {
          var pt = map.getLonLatFromPixel(e.xy);
          pt = new OpenLayers.Geometry.Point(pt.lon,pt.lat).transform(proj900913,proj4326);
          parcelInfoStore.setBaseParam('point',pt.x + ',' + pt.y);
          parcelInfoStore.setBaseParam('click','foo');
          parcelInfoStore.load();
        });

        // Sync the parcel listing w/ every map action.
        map.events.register('moveend',this,function(e) {
          parcelsOnMapGridPanel.getStore().load();
        });

        if (cp.get('parcelNum')) {
          parcelInfoStore.setBaseParam('query',cp.get('parcelNum'));
          parcelInfoStore.setBaseParam('point','');
          parcelInfoStore.setBaseParam('click','');
          parcelInfoStore.load();
        }
        else {
          map.zoomToExtent(new OpenLayers.Bounds(-71.564868011524,41.995072541334,-71.291583099426,42.183100716774).transform(proj4326,proj900913));
        }

        var soilsHTML = [];
        for (var i in soilsLegend) {
          soilsHTML.push('<td style="border:1px solid gray;width:15px;background:' + soilsLegend[i] + '"></td><td class="x-form-cb-label">&nbsp;' + i + '</td>');
        } 

        new Ext.Panel({
           renderTo       : 'parcelControls'
          ,border         : false
          ,layout         : 'column'
          ,hidden         : !showUnregulatedRadioGroup
          ,items          : [
            {
               layout         : 'form'
              ,labelSeparator : ''
              ,labelWidth     : 115
              ,border         : false
              ,items          : [
                new Ext.form.RadioGroup({
                   fieldLabel : 'Show Unregulated Parcels?'
                  ,id         : 'showUnregulatedRadioGroup'
                  ,columns    : [50,30]
                  ,items      : [
                     {boxLabel : 'Yes',name : 'showUnregulatedRadioGroup',id : 'showUnregulatedYes',checked : unregulatedVisible}
                    ,{boxLabel : 'No' ,name : 'showUnregulatedRadioGroup',id : 'showUnregulatedNo' ,checked : !unregulatedVisible}
                  ]
                  ,listeners  : {change : function(rg,radio) {
                    unregulatedVisible = radio.id == 'showUnregulatedYes';
                    cp.set('unregulatedVisible',radio.id == 'showUnregulatedYes' ? 'yes' : 'no')
                    parcelsOnMapGridPanel.getStore().load();
                  }}
                })
              ]
            }
          ]
        });

        new Ext.Panel({
           renderTo       : 'mapControls'
          ,border         : false
          ,layout         : 'column'
          ,items          : [
            {
               layout         : 'form'
              ,columnWidth    : <?php echo $_REQUEST['page'] == 'introLocation' ? 0.5 : "'auto'"?>
              ,labelSeparator : ''
              ,labelWidth     : 115
              ,border         : false
              ,items          : [
                new Ext.form.RadioGroup({
                   fieldLabel : <?php echo json_encode($glossary['Show Soil Groups']['a'])?> + '?'
                  ,id         : 'showSoilTypesRadioGroup'
                  ,items      : [
                     {boxLabel : 'Yes',name : 'showSoilTypesRadioGroup',id : 'showSoilTypesYes',checked : soilsVisible}
                    ,{boxLabel : 'No' ,name : 'showSoilTypesRadioGroup',id : 'showSoilTypesNo' ,checked : !soilsVisible}
                  ]
                  ,columns    : [50,50]
                  ,listeners  : {change : function(rg,radio) {
                    map.getLayersByName('soils')[0].setVisibility(radio.id == 'showSoilTypesYes');
                    if (radio.id == 'showSoilTypesYes') {
                      Ext.getCmp('soilsLegend').show();
                    }
                    else {
                      Ext.getCmp('soilsLegend').hide();
                    }
                    cp.set('soilsVisible',radio.id == 'showSoilTypesYes' ? 'yes' : 'no');
                  },afterrender : function() {
<?php
  foreach ($glossary as $k => $v) {
    $tNoSpace = str_replace(' ','',$k);
    echo '$(\'a#glossary_t_'.$tNoSpace.'\').click(function(e){e.preventDefault();}).hover(function(e){$(\'#glossary_d_'.$tNoSpace.'\').show();}, function(e){$(\'#glossary_d_'.$tNoSpace.'\').hide();});'."\n";
  }
?>
                  }}
                })
                ,{
                   border : false
                  ,id     : 'soilsLegend'
                  ,hidden : !soilsVisible
                  ,html   : '<table><tr>' + soilsHTML.join('<td class="x-form-cb-label" style="width:8px">&nbsp</td>') + '</tr></table>'
                }
              ]
            }
            ,{
               border      : false
              ,columnWidth : <?php echo $_REQUEST['page'] == 'introLocation' ? 0.5 : "'auto'"?>
              ,bodyStyle   : 'padding:2px 0 0 8px'
              ,html        : '<table style="padding:0;width:100%"><tr><td align=right><table><tr><td class="x-form-cb-label" style="border:2px solid #FF0000;width:15px">&nbsp;</td><td class="x-form-cb-label">&nbsp;<strong>Town boundaries</strong></tr><tr><td style="height:5px"></td></tr><tr><td class="x-form-cb-label" style="border:2px solid #7F7F7F;width:15px">&nbsp;</td><td class="x-form-cb-label">&nbsp;<strong>Watershed boundary</strong></tr></table></td></tr></table>'
            }
          ]
        });

        Ext.defer(function() {
          var divs = document.getElementsByTagName('div');
          for (var i = 0; i < divs.length; i++) {
            if (new RegExp(/^gmnoprint$/).test(divs[i].className)) {
              divs[i].parentNode.removeChild(divs[i]);
              map.googleLinkRemoved = true;
            }
          }
        },1000);

        document.getElementById('searchField').style.visibility = 'visible';
        document.getElementById('resetButton').style.visibility = 'visible';
        document.getElementById('parcelsOnMapGridPanel').style.visibility = 'visible';
        document.getElementById('map').style.visibility = 'visible';
        document.getElementById('parcelInfo').style.visibility = 'visible';

<?php
  if ($alertNoParcelNum) {
?>
        Ext.Msg.alert('No parcel selected',"You were brought back to this page because you need to select a parcel before continuing.");
<?php
  }
?>
      }
    </script>

    <style>
      #locationDiv {
        width    : 860px;
        height   : 450px;
        position : relative;
      }
      #searchField {
        position   : absolute;
        left       : 11px;
        top        : 6px;
        visibility : hidden;
      }
      #resetButton {
        position   : absolute;
        left       : 450px;
        top        : 1px;
        visibility : hidden;
      }
      #parcelsOnMapGridPanel {
        position   : absolute;
        left       : 11px;
        top        : 42px;
        width      : 207px;
        height     : 354px;
        border     : 1px solid #99BBE8;
        visibility : hidden;
      }
      #map {
        position   : absolute;
        left       : 231px;
        top        : 42px;
        width      : <?php echo $_REQUEST['page'] == 'introLocation' ? 231 + 389 : 389?>px;
        height     : 354px;
        border     : 1px solid #99BBE8;
        visibility : hidden;
      }
      #parcelInfo {
        position   : absolute;
        left       : 632px;
        top        : 2px;
        width      : 219px;
        visibility : hidden;
      }
      #mapControls {
        position   : absolute;
        left       : 232px;
        top        : 400px;
        width      : <?php echo $_REQUEST['page'] == 'introLocation' ? 231 + 389 : 389?>px;
      }
      #parcelControls {
        position   : absolute;
        left       : 11px;
        top        : 400px;
        width      : 207px;
      }
    </style>

    <div id="site">
<?php include_once('header.php')?>
        <div id="content">

            <div class="home-screen clearfix">

                <div class="left-column" style="width: 100% !important;">
                    <h2>Please select your parcel on the map below</h2>
<?php
  if ($_REQUEST['page'] == 'introLocation') {
?>
                    <table style="position: absolute; margin-top: -40px; margin-left: 570px;" id="blue-box">
                      <tr><th><div id="step-one" class="progress-bar">&nbsp;</div></th></tr>
                    </table>
<?php
  }
?>
                    <p style="font-weight: bold; margin-top: 20px;">For help navigating the map, <a class="info" id="navigating the map" href="#">click here</a>.</p>
		    <div id="locationDiv">
                      <div id="loading"><span id="loading-message">Loading. Please wait...</span></div>
                      <div id="searchField"></div>
                      <div id="resetButton"></div>
                      <div id="parcelsOnMapGridPanel"></div>
                      <div id="map"></div>
                      <div id="parcelInfo"></div>
                      <div id="mapControls">
<?php echo $glossary['Show Soil Groups']['div']?>
                      </div>
                      <div id="parcelControls"></div>
                    </div>
		    <p style="font-weight: bold; font-size: 14px;">Once you have selected your parcel, click next.</p>
		    <a id="prevStep" href="#"><img src="images/back_but.png" style="vertical-align: top; float: left; margin-top: 20px;" alt="Back" title="Back" /></a>
		    <a id="nextStep" href="javascript:void(0)"><img id="nextButton" src="images/next_but_grey.png" style="vertical-align: top; margin-left: 570px; margin-top: 20px;" alt="Next" title="Next" /></a>
               	</div>

            </div>

        </div>
<?php include_once('footer.php')?>
    </div>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript" src="./js/OpenLayers-2.12-rc7/OpenLayers-closure.js"></script>
    <script type="text/javascript" src="./js/ext-3.4.0/adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="./js/ext-3.4.0/ext-all.js"></script>
    <script type="text/javascript" src="./js/ext-3.4.0/SearchField.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        var clickHereLinks = initClickHereLinks('introLocation');
        infoWindow = $('table#info-window');
        $('a.info').click(function(e){
          e.preventDefault();
          $('table#info-window tr:eq(1) td:first').html(clickHereLinks[$(this).attr('id')]);
          infoWindow.show()
        });
        $('table#info-window tr td a').click(function(e){
          e.preventDefault();
          infoWindow.hide();
        });
        $('body').live('keydown', function (e) {
            if (infoWindow.css('display') != 'none'){
                var charCode = e.charCode || e.keyCode;
                if (charCode == 27)
                    infoWindow.css('display', 'none');
            }
        });
      });
    </script>
    <table id="info-window">
      <tr><td style="margin:0;padding:4px 7px 0 0;text-align:right;font-size: 16px;font-weight:bold;"><a href="" style="text-decoration:none;">X</a></td></tr>
      <tr><td style="padding-top:0;"></td></tr>
      <tr><td style="text-align: center; padding: 0;"><a href="">close</a></td></tr>
    </table>
  </body>
